﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using Casamiel.Domain.Response;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Casamiel.Domain;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// 
    /// </summary>
    public sealed  class GetDayProductListByStoreIdCommandHandler:BaseCommandHandler,IRequestHandler<GetDayProductListByStoreIdCommand,BaseResult<List<ProductBaseRsp>>>
    {
        private readonly IGoodBaseRepository _goodBaseRepository;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="goodBaseRepository"></param>
        /// <param name="netICService"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="settings"></param>
        public GetDayProductListByStoreIdCommandHandler(IGoodBaseRepository goodBaseRepository,INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> settings) : base(netICService, httpClientFactory, settings)
        {
            _goodBaseRepository = goodBaseRepository;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<BaseResult<List<ProductBaseRsp>>> Handle(GetDayProductListByStoreIdCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var url = "CakeMall/v1/Goods/GetListByIds";
            var ProductList = await _goodBaseRepository.GetProductIDsV2Async<ICasaMielSession>(request.StoreId).ConfigureAwait(false);
            if (ProductList == null)
            {
                return new BaseResult<List<ProductBaseRsp>>(null, 0, "");
            }
            var data = new { productIds = string.Join(',', ProductList.ToArray()) };
            var rsp = await PostThirdApiAsync<List<ProductBaseRsp>>(url, JsonConvert.SerializeObject(data)).ConfigureAwait(false);
            return rsp;
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            //if (dynamicdata["resultNo"].ToString() == "00000000")
            //{
            //    var entity = JsonConvert.DeserializeObject<List<ProductBaseRsp>>(dynamicdata["data"].ToString());
            //    return new BaseResult<List<ProductBaseRsp>>(entity, 0, "");
            //}
            //return new BaseResult<List<ProductBaseRsp>>(null, 999, dynamicdata["resultRemark"].ToString());
        }
    }
}
